package com.ayit.klog.klog;

import android.util.Log;

import com.ayit.klog.DateTimeUtil;
import com.ayit.klog.KLog;
import com.ayit.klog.KLogUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import static com.ayit.klog.DateTimeUtil.data_format_str_5;

/**
 * Created by zhaokaiqiang on 15/11/18.
 */
public class JsonLog {


    public static void printJson(String tag, String msg, String headString) {
        String message;

        try {
            if (msg.startsWith("{")) {
                JSONObject jsonObject = new JSONObject(msg);
                message = jsonObject.toString(KLog.JSON_INDENT);
            } else if (msg.startsWith("[")) {
                JSONArray jsonArray = new JSONArray(msg);
                message = jsonArray.toString(KLog.JSON_INDENT);
            } else {
                message = msg;
            }
        } catch (JSONException e) {
            message = msg;
        }

//        KLogUtil.printLine(tag, true);
        message = headString + KLog.LINE_SEPARATOR + message;
        String[] lines = message.split(KLog.LINE_SEPARATOR);
        StringBuilder sb = new StringBuilder();
        sb.append(KLogUtil.getPrintLine(tag,true));
        sb.append(KLog.LINE_SEPARATOR);
        for (String line : lines) {
            if(KLog.IS_SHOW_LOG){
                Log.d(tag, "║ " + line);
            }
//            KLog.writeFile(DateTimeUtil.formatDateTime(System.currentTimeMillis(),data_format_str_5) +" ║ " + line);
            sb.append(DateTimeUtil.formatDateTime(System.currentTimeMillis(),data_format_str_5) +" ║ " + line);
            sb.append(KLog.LINE_SEPARATOR);
        }
//        KLogUtil.printLine(tag, false);
        
        sb.append(KLogUtil.getPrintLine(tag,false));
//        sb.append(KLog.LINE_SEPARATOR);
        KLog.writeFile(false,sb.toString());
        
    }
}
